package com.yqy.spring.bank.service.impl;

import com.yqy.spring.bank.dao.AccountDao;
import com.yqy.spring.bank.pojo.Account;
import com.yqy.spring.bank.service.AccountService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

//@Transactional
@Service("accountService1")
public class AccountServiceImpl1 implements AccountService {
    @Resource(name="accountDao")
    private AccountDao accountDao;
    @Override
    public void transfer(String fromAccountId, String toAccountId, double money) {
        //查询账户余额是否充足
        Account fromAct = accountDao.selectById(fromAccountId);
        System.out.println("正在校验余额......");
        if (fromAct.getBalance()<money){
            throw new RuntimeException("账户余额不足！");
        }
        //开始转账
        Account toAct = accountDao.selectById(toAccountId);
        fromAct.setBalance(fromAct.getBalance()-money);
        toAct.setBalance(toAct.getBalance()+money);
        //下面这两条DML语句如果不能保证同时成功和同时失败，就可能造成数据丢失
        int count1 = accountDao.updateAccount(fromAct);
/**
 *String s = null;
 * s.toString();
 */
        int count2=accountDao.updateAccount(toAct);
        if (count1+count2!=2){
            throw new RuntimeException("转账异常，请联系银行！");
        }else {
            System.out.println("转账成功！");
        }
    }
    @Resource(name="accountService2")
    private AccountService accountServiceImpl2;
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void save(Account act) {
        // 这里调用dao的insert方法。
        accountDao.insert(act); // 保存act-003账户
        // 创建账户对象
        Account act2 = new Account("act-004", 1000.0);
        try {
            accountServiceImpl2.save(act2); // 保存act-004账户
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 继续往后进行我当前1号事务自己的事儿。
    }
}
